#ifndef __BASE_SEM_H__
#define __BASE_SEM_H__

#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <ctime>
#include <errno.h>
#include <stdint.h>

class BaseSemaphore {
public:
	BaseSemaphore() {
		sem_init(&_sem, 0, 0 );
	}

	~BaseSemaphore() {
		sem_destroy(&_sem);
	}

	void wait() {
		sem_wait(&_sem);
	}

	int32_t wait_timeout(uint32_t sec) {
		struct timespec ts;
		clock_gettime(CLOCK_REALTIME, &ts);
		ts.tv_sec += sec;
		int ret = 0;
		while ((ret = sem_timedwait(&_sem, &ts)) == -1 && errno == EINTR)
		        continue;
		if (-1 == ret) {
			if (errno == ETIMEDOUT)
				return 1;
			else
				return -1;
		}

		return ret;
	}

	void post() {
		sem_post(&_sem);
	}

	//void set_count(int32_t cnt) {
	//	sem_post_multiple(&_sem, cnt);
	//}

private:
	sem_t _sem;
};
#endif  // __BASE_SEM_H__
